#include <iostream>
#include "person.h"

using namespace std;

template<typename T>
class sp {
private:
    T *p;
public:
    sp(T *other) {
        cout << "sp copy construct..." << endl;
        p = other;
        p->incStrong();
    }

    ~sp() {
        if (p) {
            p->decStrong();
            if (p->getStrongCount() == 0) {
                delete p;
                p = NULL;
            }
        }
    }

    sp(const sp &other) {
        cout << "sp(const sp &other)..." << endl;
        p = other.p;
        p->incStrong();
    }

    T *operator->() {
        return p;
    }

    T& operator*() {
        return *p;
    }
};

//void test_func(void) {
//    Person *p = new Person;
//    p->printInfo();

//    Person per("zhangsan", 16);
//    per.printInfo();

//    sp s = new Person("zhangsan", 16);
//    s->printInfo();
//}

void test_func(sp<Person> &other) {
    sp<Person> s = other;
    cout << "2.count = " << s->getStrongCount() << endl;
}

int main() {
//    test_func();

    sp<Person> other = new Person();
    cout << "1.count = " << other->getStrongCount() << endl;
    cout << "1.count = " << (*other).getStrongCount() << endl;
    test_func(other);
    cout << "3.count = " << other->getStrongCount() << endl;

    return 0;
}
